package util

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
)

// 封装POST请求
func Post(url string, data interface{}) ([]byte, error) {
	jsonStr, _ := json.Marshal(data)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	if err != nil {
		return []byte(""), errors.New("参数有误")
	}
	req.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return []byte(""), errors.New("请求失败")
	}
	defer res.Body.Close()
	body, _ := ioutil.ReadAll(res.Body)
	return body, nil
}

// 封装GET请求
func Get(url string) ([]byte, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return []byte(""), errors.New("参数有误")
	}
	// 如果需要，可以在这里设置请求头
	// req.Header.Set("Header-Name", "value")

	client := &http.Client{}
	res, err := client.Do(req)
	if err != nil {
		return []byte(""), errors.New("请求失败")
	}
	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return []byte(""), errors.New("读取响应失败")
	}
	return body, nil
}
